use std::fmt::Debug;
use std::sync::Arc;
use async_trait::async_trait;
use anyhow::Result;
use redis::{aio::Connection, AsyncCommands, Client};
use serde::{Deserialize, Serialize};
use tracing::{debug, error, info, warn};

use crate::persistence::{EventStore, PersistenceError, PersistentEvent, PersistentState};

/// Redis-based event store implementation
pub struct RedisEventStore<E, S>
where
    E: PersistentEvent + for<'de> Deserialize<'de> + Serialize + Clone + Debug + 'static,
    S: PersistentState + for<'de> Deserialize<'de> + Serialize + Clone + Debug + 'static,
{
    /// Redis client
    client: Client,
    
    /// Key prefix for events
    events_prefix: String,
    
    /// Key prefix for snapshots
    snapshots_prefix: String,
    
    /// Interval between snapshots (0 means no snapshots)
    snapshot_interval: u64,
    
    /// Phantom data for generics
    _marker_e: std::marker::PhantomData<E>,
    _marker_s: std::marker::PhantomData<S>,
}

impl<E, S> RedisEventStore<E, S>
where
    E: PersistentEvent + for<'de> Deserialize<'de> + Serialize + Clone + Debug + 'static,
    S: PersistentState + for<'de> Deserialize<'de> + Serialize + Clone + Debug + 'static,
{
    /// Create a new Redis event store
    pub fn new(
        connection_string: &str,
        events_prefix: &str,
        snapshots_prefix: &str,
        snapshot_interval: u64,
    ) -> Result<Self, PersistenceError> {
        let client = Client::open(connection_string)
            .map_err(|e| PersistenceError::General(e.into()))?;
        
        Ok(Self {
            client,
            events_prefix: events_prefix.to_string(),
            snapshots_prefix: snapshots_prefix.to_string(),
            snapshot_interval,
            _marker_e: std::marker::PhantomData,
            _marker_s: std::marker::PhantomData,
        })
    }
    
    /// 获取事件的Redis键
    fn get_events_key(&self, actor_id: &str) -> String {
        format!("{}:{}", self.events_prefix, actor_id)
    }
    
    /// 获取快照的Redis键
    fn get_snapshot_key(&self, actor_id: &str) -> String {
        format!("{}:{}", self.snapshots_prefix, actor_id)
    }
    
    /// 获取Redis连接
    async fn get_connection(&self) -> Result<Connection, PersistenceError> {
        self.client
            .get_async_connection()
            .await
            .map_err(|e| PersistenceError::General(e.into()))
    }
}

#[async_trait]
impl<E, S> EventStore for RedisEventStore<E, S>
where
    E: PersistentEvent + for<'de> Deserialize<'de> + Serialize + Clone + Debug + 'static,
    S: PersistentState + for<'de> Deserialize<'de> + Serialize + Clone + Debug + 'static,
{
    type Event = E;
    type State = S;
    
    fn snapshot_interval(&self) -> u64 {
        self.snapshot_interval
    }
    
    async fn save_event(&self, actor_id: &str, event: &Self::Event, index: u64) -> Result<(), PersistenceError> {
        let mut conn = self.get_connection().await?;
        
        let events_key = self.get_events_key(actor_id);
        let json_data = serde_json::to_string(event)
            .map_err(|e| PersistenceError::WriteError(format!("Failed to serialize event: {}", e)))?;
        
        // 使用Sorted Set存储事件，以索引为分数
        let _: () = conn.zadd(&events_key, json_data, index as f64)
            .await
            .map_err(|e| PersistenceError::WriteError(format!("Failed to save event to Redis: {}", e)))?;
        
        debug!("Saved event for actor {}, index {}, type {}", actor_id, index, event.event_type());
        Ok(())
    }
    
    async fn get_events(&self, actor_id: &str, start_index: u64) -> Result<Vec<Self::Event>, PersistenceError> {
        let mut conn = self.get_connection().await?;
        
        let events_key = self.get_events_key(actor_id);
        
        // 从Sorted Set获取指定分数范围的事件
        let json_events: Vec<String> = conn.zrangebyscore(&events_key, start_index as f64, "+inf")
            .await
            .map_err(|e| PersistenceError::ReadError(format!("Failed to read events from Redis: {}", e)))?;
        
        let mut events = Vec::with_capacity(json_events.len());
        for json_data in json_events {
            let event = serde_json::from_str(&json_data)
                .map_err(|e| PersistenceError::ReadError(format!("Failed to deserialize event: {}", e)))?;
            events.push(event);
        }
        
        debug!("Retrieved {} events for actor {} from index {}", events.len(), actor_id, start_index);
        Ok(events)
    }
    
    async fn save_snapshot(&self, actor_id: &str, state: &Self::State) -> Result<(), PersistenceError> {
        let mut conn = self.get_connection().await?;
        
        let snapshot_key = self.get_snapshot_key(actor_id);
        let json_data = serde_json::to_string(state)
            .map_err(|e| PersistenceError::SnapshotWriteError(format!("Failed to serialize state: {}", e)))?;
        
        // 存储快照，Redis简单字符串
        let _: () = conn.set(&snapshot_key, json_data)
            .await
            .map_err(|e| PersistenceError::SnapshotWriteError(format!("Failed to save snapshot to Redis: {}", e)))?;
        
        debug!("Saved snapshot for actor {}, version {}", actor_id, state.version());
        Ok(())
    }
    
    async fn get_snapshot(&self, actor_id: &str) -> Result<Option<Self::State>, PersistenceError> {
        let mut conn = self.get_connection().await?;
        
        let snapshot_key = self.get_snapshot_key(actor_id);
        
        // 获取快照数据
        let json_data: Option<String> = conn.get(&snapshot_key)
            .await
            .map_err(|e| PersistenceError::SnapshotReadError(format!("Failed to read snapshot from Redis: {}", e)))?;
        
        if let Some(json_data) = json_data {
            let state = serde_json::from_str(&json_data)
                .map_err(|e| PersistenceError::SnapshotReadError(format!("Failed to deserialize state: {}", e)))?;
            debug!("Retrieved snapshot for actor {}", actor_id);
            Ok(Some(state))
        } else {
            debug!("No snapshot found for actor {}", actor_id);
            Ok(None)
        }
    }
} 